using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Framework.Library.Components.Commands;
using Framework.Library;
using Framework.Library.Components.Security;
using Framework.Library.Utilities.Database;
using System.Data.SqlClient;
using Framework.Library.Components.Database;
using Framework.Library.Utilities;

namespace Framework.Portal.Administrator.Database
{
    public partial class StoreAction : AuthenticatedControl
    {
        _StoredProcedure objProc = new _StoredProcedure();

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);
            if (!IsPostBack)
            {
                lblCommandName.Text = AppEnv.CommandName();
                objProc.ID = Convert.ToInt64(Request["id"].ToString());
                objProc.LoadProperties();

                //switch on action
                switch (Request.QueryString["action"].ToString())
                {
                    case "drop":
                        lblDropProcName.Text = objProc.Owner + "." + objProc.Name;
                        pnlDrop.Visible = true;
                        break;
                    case "rename":
                        pnlRename.Visible = true;
                        lblRenProcName.Text = objProc.Owner + "." + objProc.Name;
                        lblOwnerNewName.Text = objProc.Owner;
                        break;
                    case "exec":
                        loadExecForm(objProc);
                        break;
                }
                lnkProcList.NavigateUrl = AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.Store));
                lnkProcDetails.NavigateUrl = AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.StoreProperty)) + "&id=" + objProc.ID;
            }
        }
        #region "Drop"

        protected void btnDrop_Click(object sender, EventArgs e)
        {
            try
            {
                objProc.ID = Convert.ToInt64(Request["id"].ToString());
                objProc.LoadProperties();

                objProc.Drop();
                Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.Store)));
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = "<p>" + ex.Message + "</p>";
            }
        }

        #endregion

        #region "Rename"

        protected void btnRename_Click(object sender, EventArgs e)
        {            
            objProc.ID = Convert.ToInt64(Request["id"].ToString());
            objProc.LoadProperties();
            try
            {

                string _procNewName = "";
                if (Info.CheckSpecialChar(txtNewName.Text))
                {
                    _procNewName = "[" + objProc.Owner + "].[" + txtNewName.Text + "]";
                }
                else
                {
                    _procNewName = objProc.Owner + "." + txtNewName.Text;
                }

                objProc.Rename(_procNewName);

                Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.Store)));
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = "<p>" + ex.Message + "</p>";
            }
        }

        #endregion

        #region "Execute"

        private void loadExecForm(_StoredProcedure myProc)
        {
            //********************************************
            //datatable definition
            DataTable datacols = new DataTable();
            datacols.Columns.Add("COLUMN_NAME", Type.GetType("System.String"));
            datacols.Columns.Add("TYPE_NAME", Type.GetType("System.String"));
            datacols.Columns.Add("NULL", Type.GetType("System.String"));
            datacols.Columns.Add("VALUE", Type.GetType("System.String"));
            datacols.Columns.Add("PRECISION", Type.GetType("System.String"));
            datacols.Columns.Add("COLUMN_TYPE", Type.GetType("System.String"));
            //********************************************

            lblExecProc.Text = myProc.Owner + '.' + myProc.Name;
            pnlExec.Visible = true;

            myProc.SetColumns();

            while (myProc.Columns.Read())
            {
                if (myProc.Columns.GetValue(4).ToString() == "1" || myProc.Columns.GetValue(4).ToString() == "2")
                {
                    DataRow myRow = datacols.NewRow();

                    myRow["COLUMN_NAME"] = myProc.Columns.GetString(3).ToString();
                    myRow["TYPE_NAME"] = myProc.Columns.GetString(6).ToString();
                    myRow["PRECISION"] = myProc.Columns.GetValue(7).ToString();
                    myRow["COLUMN_TYPE"] = myProc.Columns.GetValue(4).ToString();

                    datacols.Rows.Add(myRow);
                }
            }

            gridColumns.DataSource = datacols;
            gridColumns.DataBind();

        }

        protected void gridColumns_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView rowView = (DataRowView)e.Row.DataItem;
            if (rowView != null)
            {
                if (rowView["COLUMN_TYPE"].ToString() == "2")
                {
                    e.Row.Visible = false;
                }
            }
        }


        protected void dataOutputParam_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            DataRowView rowView = (DataRowView)e.Item.DataItem;
            if (rowView != null)
            {
                Label lblParamName = (Label)e.Item.FindControl("lblParamName");
                lblParamName.Text = rowView["PARAM_NAME"].ToString();
                Label lblParamValue = (Label)e.Item.FindControl("lblParamValue");
                lblParamValue.Text = rowView["PARAM_VALUE"].ToString();
            }
        }

        protected void btnExecute_Click(object sender, EventArgs e)
        {
            pnlResults.Visible = true;
            objProc.ID = Convert.ToInt64(Request["id"].ToString());
            objProc.LoadProperties();
            
            SqlCommand myCommand;
            myCommand = objProc.GetCommand();
            myCommand.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

            //cycle
            foreach (GridViewRow objRow in gridColumns.Rows)
            {
                TextBox myValue = (TextBox)objRow.FindControl("txtValue");

                if (myValue != null)
                {

                    SqlDbType myType = objProc.ColumnType(objRow.Cells[2].Text);

                    switch (objRow.Cells[0].Text.ToString())
                    {
                        case "1":
                            //value
                            myCommand.Parameters.Add(objRow.Cells[1].Text, myType, Convert.ToInt32(objRow.Cells[3].Text)).Value = (object)myValue.Text;
                            break;
                        case "2":
                            //output value
                            myCommand.Parameters.Add(objRow.Cells[1].Text, myType, Convert.ToInt32(objRow.Cells[3].Text)).Direction = ParameterDirection.Output;
                            break;
                    }
                }
            }

            SqlDataReader myReader = myCommand.ExecuteReader();

            gridResults.DataSource = myReader;
            gridResults.DataBind();

            myReader.Close();

            DataTable dataParams = outputDataTable();

            //for each output parameter print the output
            foreach (SqlParameter myParam in myCommand.Parameters)
            {
                if (myParam.Direction == ParameterDirection.Output)
                {
                    //add values
                    DataRow rowParam = dataParams.NewRow();
                    rowParam["PARAM_NAME"] = myParam.ParameterName;
                    rowParam["PARAM_VALUE"] = myParam.Value;
                    dataParams.Rows.Add(rowParam);
                }
            }

            lblRETURN_VALUE.Text = myCommand.Parameters["@RETURN_VALUE"].Value.ToString();

            dataOutputParam.DataSource = dataParams;
            dataOutputParam.DataBind();
        }



        private DataTable outputDataTable()
        {
            DataTable dataParams = new DataTable();
            dataParams.Columns.Add("PARAM_NAME", Type.GetType("System.String"));
            dataParams.Columns.Add("PARAM_VALUE", Type.GetType("System.String"));
            return dataParams;
        }

        #endregion
    }
}